"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const koa_router_1 = __importDefault(require("koa-router"));
const DBTool_1 = __importDefault(require("../com/DBTool/DBTool"));
const configTool_1 = __importDefault(require("../com/configTool"));
const koa_body_1 = __importDefault(require("koa-body"));
const DBConnectTool_1 = __importDefault(require("../com/DBTool/DBConnectTool"));
const index_1 = __importDefault(require("../lib/FSTool/EncryptFiles/threadEncryptFiles/index"));
const webSocketTool_1 = __importDefault(require("../com/webSocketTool/webSocketTool"));
const getFilePathList_1 = __importDefault(require("../lib/FSTool/getFilePathList"));
const LogTool_1 = __importDefault(require("../com/LogTool/LogTool"));
const ManageRoutes = new koa_router_1.default({ prefix: '/manage' });
ManageRoutes
    .get('/getDBInfoList', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let fileInfoList = await DBTool_1.default.getDBInfoList() || [];
    const normalDBExt = configTool_1.default.baseConfig.normalDBExt;
    const encryptDBExt = configTool_1.default.baseConfig.encryptDBExt;
    const regexStr = `-MD5-..?\\.(${normalDBExt}|${encryptDBExt})$`;
    const regex = new RegExp(regexStr);
    fileInfoList = fileInfoList.filter(item => !(regex.test(item.filePath)));
    ctx.body = JSON.stringify(fileInfoList);
})
    .get('/getDBPathTree', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    let res = await dbTool.getDBPathTree();
    ctx.body = JSON.stringify(res);
})
    .get('/getFileListByPath', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, path } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    let res = await dbTool.getDirListByPath(path);
    ctx.body = JSON.stringify(res);
})
    .get('/getDirInfo', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, dirPath } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    let res = await dbTool.getDirInfo(dirPath);
    ctx.body = JSON.stringify(res);
})
    .post('/uploadDB', (0, koa_body_1.default)({
    multipart: true,
    formLimit: '2000mb',
    jsonLimit: '20mb',
    formidable: {
        keepExtensions: true,
        maxFileSize: 8 * 1024 * 1024 * 1024,
        filename: (name, ext, part) => {
            return `${part.originalFilename?.replace(/[\/\\]/g, '_')}_${Date.now()}${ext}`;
        },
        onFileBegin(name, file) {
            const upload_dir = path_1.default.join(configTool_1.default.appBasePath, '/temp/fileDB/upload');
            file.filepath = path_1.default.join(upload_dir, file.originalFilename);
        }
    }
}), async (ctx) => {
    const file = ctx.request.files?.file;
    if (!file) {
        ctx.status = 400;
        ctx.body = { ok: false, message: '缺少 file 字段' };
        return;
    }
    ctx.set('content-type', 'application/json;charset=utf-8');
    ctx.body = JSON.stringify({
        ok: true,
        filePath: file.filepath,
        fileName: path_1.default.basename(file.filepath),
        size: file.size
    });
})
    .get('/createDB', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, targetDirectory, mataData } = ctx.request.query;
    if (mataData) {
        mataData = JSON.parse(mataData);
    }
    let msg = await DBTool_1.default.createDB(DBName, targetDirectory, mataData);
    ctx.body = JSON.stringify({ msg });
})
    .get('/appendFile', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, targetDirectory, currentDirectory } = ctx.request.query;
    let msg = await DBTool_1.default.appendFile(DBName, targetDirectory, currentDirectory);
    await DBConnectTool_1.default.reConnect(DBName);
    ctx.body = JSON.stringify({ msg });
})
    .get('/clearFileDate', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    await DBConnectTool_1.default.reConnect(DBName);
    let res = await dbTool.clearFileDate();
    ctx.body = JSON.stringify(res);
})
    .get('/wipeCache', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    await DBConnectTool_1.default.reConnect(DBName);
    let res = await dbTool.wipeCache();
    ctx.body = JSON.stringify(res);
})
    .get('/deleteByFullPath', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, fullPath } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    await DBConnectTool_1.default.reConnect(DBName);
    let res = await dbTool.deleteByFullPath(fullPath);
    ctx.body = JSON.stringify(res);
})
    .get('/deleteByDir', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, directory } = ctx.request.query;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    await DBConnectTool_1.default.reConnect(DBName);
    let res = await dbTool.deleteByDir(directory);
    ctx.body = JSON.stringify(res);
})
    .get('/exportDB', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, targetDirectory } = ctx.request.query;
    let res = await DBTool_1.default.exportDB(DBName, targetDirectory);
    ctx.body = JSON.stringify({ res });
})
    .get('/deleteDB', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName } = ctx.request.query;
    if (DBName) {
        await DBConnectTool_1.default.closeAll();
        let result = await DBTool_1.default.deleteDB(DBName);
        ctx.body = JSON.stringify({ result });
    }
    else {
        ctx.status = 404;
    }
})
    .get('/getFileBySearch', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, text } = ctx.request.query;
    if (DBName && text) {
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        let list = await dbTool.getFileListBySearch(text);
        list.map((item) => item.ext = path_1.default.extname(item.file_name));
        ctx.body = JSON.stringify(list);
    }
    else {
        ctx.status = 404;
    }
})
    .get('/getMataData', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName } = ctx.request.query;
    if (DBName) {
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        ctx.body = await dbTool.getMataData();
    }
    else {
        ctx.status = 404;
    }
})
    .get('/threadEncryptFiles', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { inputPath, outPutPath, passWorld, threadNum } = ctx.request.query;
    if (inputPath && outPutPath && passWorld && threadNum) {
        const filePathList = await (0, getFilePathList_1.default)(inputPath);
        const beginTime = new Date().getTime();
        const mes = await (0, index_1.default)(filePathList, inputPath, outPutPath, passWorld, (e) => {
            e.action = 'runProgress';
            e.passTime = Math.ceil((new Date().getTime() - beginTime) / 1000);
            webSocketTool_1.default.sendToAllUser(JSON.stringify(e));
        }, threadNum);
        ctx.body = JSON.stringify(mes);
    }
    else {
        ctx.status = 400;
        ctx.body = JSON.stringify({ message: '参数错误' });
    }
})
    .get('/getClientServerWebLog', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    ctx.status = 200;
    const logList = await LogTool_1.default.queryLog('info');
    ctx.body = logList
        .filter((item) => item.message.startsWith('http '))
        .map((item) => JSON.parse(item.message.replace('http ', '')));
})
    .get('/getManageServerWebLog', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    ctx.status = 200;
    const logList = await LogTool_1.default.queryLog('warn');
    ctx.body = logList
        .filter((item) => item.message.startsWith('http '))
        .map((item) => JSON.parse(item.message.replace('http ', '')));
})
    .get('/getLogSummary', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    const logSummaryMap = new Map();
    let logList = await LogTool_1.default.queryLog('info');
    logList = logList.filter((item) => item.message.startsWith('http client '))
        .map((item) => JSON.parse(item.message.replace('http client ', '')));
    logList.forEach((item) => {
        const ip = item.ip;
        const start = new Date(item.start).toDateString();
        const key = `${ip}-${start}`;
        if (logSummaryMap.has(key)) {
            const value = logSummaryMap.get(key);
            value.count++;
        }
        else {
            const isoDate = new Date(start).toISOString().replace(/T.*/, '');
            logSummaryMap.set(key, { ip, isoDate, count: 1 });
        }
    });
    ctx.body = Array.from(logSummaryMap.values());
})
    .post('/setMataData', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    let { DBName, mataData } = ctx.request.body;
    let dbTool = await DBConnectTool_1.default.openDB(DBName);
    if (mataData) {
        mataData = JSON.parse(mataData);
    }
    let msg = await dbTool.addItemToMataData(mataData);
    ctx.body = JSON.stringify({ msg });
});
exports.default = ManageRoutes;
